<?
/*
 * 公用函數庫
 * 更新:2006.10.10
 * 作者:夏一平
 */
class g
{
    /*
     * 功能:彈出對話框
     * 參數:$msg		提示信息
     * 		$script	頭尾是否加上script 1:加 0:不加
     * 返回:string
     */
    static public function alert($msg, $script= 1)
    {
        $search		= array ('\\',"\n","\t","\r","\b","\f","'");
        $replace	= array ('\\\\','\\n','\\t','\\r','\\b','\\f',"\'");
        $msg		= str_replace($search, $replace, $msg);
        $msg		= str_replace(array(chr(0x08), chr(0x0C)), array('\b','\f'), $msg);
        $rs			= "alert('" . $msg . "');\n";
        if($script)
        	$rs= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<script type=\"text/javascript\">\n" . $rs . "\n</script>";
        return $rs;
    }
    static public function msg($msg, $script= 1)
    {
        return self::alert($msg, $script);
    }
    /*
     * 功能：PHP加好密JS去解
     */
    static public function phpEnCode($str,$len=2)
    {
        $key= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $h= $key[mt_rand(0, strlen($key)-1)];
        $h_l= ord($h)%$len;
        $b1_64= base64_encode($str);
        
        $t= substr($b1_64, mt_rand(0, strlen($b1_64) - $h_l), $h_l);
        return $h .str_replace('=','', base64_encode($t . $h . $b1_64));
    }
    static public function phpDeCode($str,$len=2)
    {
        return base64_decode(substr(base64_decode(substr($str,1)),1+ord($str[0])%$len));
    }
    /*
	 * 转码
	 */
    static public function mb(&$string,$to_encoding="UTF-8",$from="GB2312")
	{
		return mb_convert_encoding($string, $to_encoding,$from);
	}
    /*
     * 功能:寫文件
     * 參數:$fileName	文件名
     * 		$content	內容
     * 返回:成功:true 失敗:false 
     */
    static public function write($fileName, $content, $type= "w")
    {
        if ($fd= fopen($fileName, $type))
        {
            $rs = fwrite($fd, $content);
            fclose($fd);
            return $rs;
        }
        return false;
    }
    /*
    * 功能:檢查目錄是否存在,沒有新建
    * 參數:$dir 	目錄相對路徑
    * 返回:ture:成功 flase:失敗 
    */
    static public function dir($dir, $recursive= false)
    {
        if (is_dir($dir))
        {
            return true;
        } else
        {
        	file_exists($dir)
        		&& unlink($dir);
        	return mkdir($dir, 0777, $recursive);
        }
    }
    /**
     * 写cookie
     */
    static public function setcookie($key,$val,$hour=1,$domain=1)
    {
        //$val = urlencode($val);
		if($domain)
        {
        	setcookie ($key, $val, time() + $hour*3600, "/", ".".SITE_DOMAIN);
        }else
        {
            setcookie ($key, $val, time() + $hour*3600);
        }
    }
	/*
	 * 功能:得到文件名
	 * 参数:$file		文件路径
	 * 		$ex			扩展名 0:不带扩展名 1:有扩展名 2:返回数组
	 * 返回:string 文件名
	 */
	static public function basename($file,$ex=0)
	{
		$rs 		   = pathinfo($file);
		$rs['name_ex'] = $rs['basename'];
		if(strstr(substr($rs['basename'],-8),'.'))
		{
			$rs['ex'] 	= $rs['extension'];
		}else
		{
			$rs['ex'] 	= '';
		}
		$rs['name']   	=$rs['ex']?substr($rs["basename"],0,- (strlen($rs["ex"]) + 1) ):$rs["basename"];
		if(empty($ex))
		{	//返回 不带扩展名
			return $rs['name'];
		}else if($ex == 1)
		{	//返回 带扩展名
			return $rs['name_ex'];
		}else
		{	//返回数组 
			$rs['dir'] 	="{$rs['dirname']}/";
			return $rs;
		}
	}
    /*
    * 功能:刪除一個目錄
    * 參數:$dir 	目錄相對路徑
    * 返回:ture:成功 flase:失敗 
    */
    static public function rmdir($path)
    {
        if(!is_dir($path) || !$handle = opendir($path))
        	return false;
        while ($val= readdir($handle))
        {
            if ($val == '.' || $val == '..')
                continue;
            $value= $path . "/" . $val;
            if(is_dir($value))
            {
                self :: rmdir($value);
            }elseif(is_file($value))
            {
                unlink($value);
            }
        }
        closedir($handle);
        return rmdir($path);
    }
    /*
     * 功能:頁面跳轉
     * 參數:$link		跳轉URL
     * 		$top		是否top
     * 返回:無 
     */
    static public function gowin($link='', $top= '', $note= '') //err
    {
        if (!$link || $top || $note)
        {
            $replace= "\t" . ($top ? "window.top." : "") . "location.href='" . $link . "';\n";
            echo "<script type=\"text/javascript\">\n";
			echo $link
					?($note
						?"if(window.confirm('{$note}')){\n{$replace}}"
						:$replace
					 )
					:"window.history.go(-1);\n";
			echo "</script>\n";
        }else
        {
            headers_sent()
            	|| header("Location: " . $link);
            echo "<meta http-equiv=\"refresh\" content=\"0;url={$link}\">\r\n";
        }
        exit();
    }
    
    /*
     * 功能:中文截割
     */
    static public function substr($string, $sublen= 20)
    {
        if ($sublen >= strlen($string))
        	return $string;
        $string = self::utf8_trim(substr($string,0,$sublen-2));
        return $string . '..';
    }
	private function utf8_trim($str) 
	{
		$len = strlen($str);
		for ($i=strlen($str)-1; $i>=0; $i-=1)
		{
			$hex .= ' '.ord($str[$i]);
			$ch = ord($str[$i]);
			if (($ch & 128)==0)
				return(substr($str,0,$i));
			if (($ch & 192)==192)
				return(substr($str,0,$i));
		}
		return($str.$hex);
	}

    static public function ip()
    {
        if (isset ($_SERVER['HTTP_CLIENT_IP']))
        {
            $hdr_ip= stripslashes($_SERVER['HTTP_CLIENT_IP']);
        } else
        {
            if (isset ($_SERVER['HTTP_X_FORWARDED_FOR']))
            {
                $hdr_ip= stripslashes($_SERVER['HTTP_X_FORWARDED_FOR']);
            } else
            {
                $hdr_ip= stripslashes($_SERVER['REMOTE_ADDR']);
            }
        }
        return $hdr_ip;
    }
	static public function isemail($email)
	{
		return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
	}
    /*
     * 功能:轉換時間
     * 參數:$t		1970年的秒數
     * 		$a		1:日期,2:日期 時間
     * 返回:無 
     */
    static public function time($t=0, $a= 2)
    {
        $t = $t ? $t :time();
		if ($a == 2)
			return date("Y-m-d H:i:s", $t);
        return date("Y-m-d", $t);
    }
    /*
     * 功能:發郵件
     */
    static public function mail($email, $subject, $msg, $sender_email= "")
    {
        $sender_email= $sender_email ? $sender_email : SITE_NAME . "<" . SITE_SYSMAIL . ">";
        //$headers = "From: $sender_email\nContent-Type: text/plain; charset=gb2312\nContent-Transfer-Encoding: 8bit";
        $headers= "From: " . $sender_email;
        //$config = $sender_email;
        mail($email, $subject, $msg, $headers);
    }
    /*
    * 功能:字節轉換
    * 參數:$size 	字節數
    * 返回:相應單位 
    */
    static public function size($size)
    {
        if ($size < 1024)
        {
            return round($size, 2) . 'Bit';
        }elseif ($size < 1024 * 1024)
        {
            $size= $size / 1024;
            return round($size, 2) . 'K';
        }elseif ($size < 1024 * 1024 * 1024)
        {
            $size= $size / 1024 / 1024;
            return round($size, 2) . 'M';
        }elseif ($size < 1024 * 1024 * 1024 * 1024)
        {
            $size= $size / 1024 / 1024 / 1024;
            return round($size, 2) . 'G';
        }elseif ($size < 1024 * 1024 * 1024 * 1024 * 1204)
        {
            $size= $size / 1024 / 1024 / 1024 / 1024;
            return round($size, 2) . 'T';
        }else
        {
            $size= $size / 1024 / 1024 / 1024 / 1024 / 1024;
            return round($size, 2) . 'P';
        }
    }
    /*
     * 
     */
    static public function enarray($array, $level= 0)
    {
        $space= '';
        for ($i= 0; $i <= $level; $i++)
	        $space .= "\t";
        $evaluate= "array\n$space(\n";
        $comma= $space;
        if (is_array($array))
        {
            foreach ($array as $key => $val)
            {
                $key= is_string($key) ? '\'' . addcslashes($key, '\'\\') . '\'' : $key;
                $val= !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\'' . addcslashes($val, '\'\\') . '\'' : $val;
                if (is_array($val))
                {
                    $evaluate .= "$comma$key => " . self :: enarray($val, $level +1);
                } else
                {
                    $evaluate .= "$comma$key => $val";
                }
                $comma= ",\n$space";
            }
        }
        $evaluate .= "\n$space)";
        return $evaluate;
    }
    /*
     *  異步  	
     */
    static public function file_get_contents($url)
    {
        //return file_get_contents($url);
        $info= parse_url($url);
        $info['port']= $info['port'] ? $info['port'] : 80;
        return self :: async_file_get_contents($info['host'], $info['path'] . ($info['query'] ? '?' . $info['query'] : ''), $info['port']);
    }
    static public function async_file_get_contents($site, $pos, $port= 80, $timeout= 5)
    {
        if (!$fp = fsockopen($site, $port, $errno, $errstr, 5))
        	return false;
        fwrite($fp, "GET /$pos HTTP/1.0\r\n\r\n");
        stream_set_timeout($fp, $timeout);
        $res= stream_get_contents($fp);
        $info= stream_get_meta_data($fp);
        fclose($fp);
        if ($info['timed_out'])
        	return false;
        return substr(strstr($res, "\r\n\r\n"), 4);
    }
}
?>
